package com.dykj.fireFighting.web.controller;

import com.alibaba.fastjson.JSONObject;

import com.dykj.fireFighting.api.base.enterprise.entity.Enterprise;
import com.dykj.fireFighting.api.base.enterprise.service.IEnterpriseService;
import com.dykj.fireFighting.api.monitoringCenter.dto.InstructionRecordDto;
import com.dykj.fireFighting.api.monitoringCenter.entity.InstructionRecord;
import com.dykj.fireFighting.api.monitoringCenter.service.InstructionRecordService;
import com.dykj.fireFighting.api.monitoringCenter.vo.InstructionRecordVo;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.constant.WebsocketConstant;
import com.dykj.fireFighting.common.core.dto.CommonDto;
import com.dykj.fireFighting.common.core.exception.BaseException;
import com.dykj.fireFighting.common.core.utils.UUIDUtils;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.common.starter.redisson.service.RedisService;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import com.dykj.fireFighting.web.base.websocket.CommonWebSocket;
import com.dykj.fireFighting.web.base.websocket.entity.MoreMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 指令执行记录接口
 *
 * @Author aixiaolan
 * @Date  2021-07-06 14:34:27
 */
@Slf4j
@Api(value = "指令执行记录接口", tags = {"指令执行记录接口"})
@RestController
@RequestMapping("/instructionRecord")
public class InstructionRecordController {

    @DubboReference
    private InstructionRecordService instructionRecordService;

    @DubboReference
    private IEnterpriseService iEnterpriseService;
    @Autowired
    private RedisService redisService;


    /**
     * 获取单位id
     * @return String
     */
    public String getEnterpriseId() {
        try {
            return Long.toString(ShiroUtil.getUser().getEnterpriseId());
        } catch (NullPointerException e) {
            e.printStackTrace();
            throw new BaseException("请登录系统");
        }
    }

    /**
     * 获取用户名称
     * @return String
     */
    public String getName() {
        try {
            return ShiroUtil.getUser().getName();
        } catch (NullPointerException e) {
            e.printStackTrace();
            throw new BaseException("请登录系统");
        }
    }


    /**
     * 指令执行记录列表
     *
     * @return
     */
    @AutoLog(value = "指令执行记录-分页列表查询")
    @ApiOperation(value = "指令执行记录分页列表", notes = "指令执行记录分页列表")
    @GetMapping("/list")
//    @RequiresPermissions("firemanger/instructionRecord/list")
    public CommonResult<PageVo<InstructionRecordVo>> treeGrid(InstructionRecordDto commonDto) {
        PageVo<InstructionRecordVo> page = instructionRecordService.pageList(commonDto);
        log.info("查岗数据条数：{},[{}]",page.getTotalCount(),commonDto.getKey());
        return CommonResult.success(page);
    }

    /**
     * 获取指令执行记录信息
     */
    @AutoLog(value = "指令执行记录-获取指令执行记录信息")
    @ApiOperation(value = "获取指令执行记录信息", notes = "获取指令执行记录信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", dataType = "String", required = true)
    @GetMapping("/info/{id}")
//    @RequiresPermissions("firemanger/instructionRecord/info")
    public CommonResult<InstructionRecord> info(@PathVariable("id") String id){
        InstructionRecord instructionRecord = instructionRecordService.getById(id);
        return CommonResult.success(instructionRecord);
    }

    /**
     * 保存指令执行记录信息
     */
    @AutoLog(value = "指令执行记录-保存指令执行记录信息")
    @ApiOperation(value = "保存指令执行记录信息", notes = "保存指令执行记录信息")
    @PostMapping("/save")
//    @RequiresPermissions("firemanger/instructionRecord/save")
    public CommonResult save(@Valid @RequestBody InstructionRecord instructionRecord) {
        try {
            // 选择的社会单位id
            String unitId = instructionRecord.getReceiveUnitId();
            // 保存查岗
            instructionRecord.setId(UUIDUtils.get32UUID());
            instructionRecord.setCreateTime(new Date());
            instructionRecord.setUpdateTime(null);
            instructionRecord.setCreateBy(getName());
            instructionRecord.setSendUnitId(getEnterpriseId());
            instructionRecord.setUnitId(unitId);
            instructionRecord.setIsDetermine(1);
            instructionRecord.setSendTime(new Date());
            boolean flagResult  =instructionRecordService.save(instructionRecord);
                if(flagResult) {
                    log.info("数据写入成功，准备推送消息");
                    List<String>unitUserIds=new ArrayList<>();
                    //获取社会单位推送用户
                    unitUserIds.addAll(instructionRecordService.getUserByUnitId(unitId));
                    MoreMessage moreMessage=new MoreMessage();
                    moreMessage.setUserIds(unitUserIds.toArray(new String[0]));
                    moreMessage.setCmd(WebsocketConstant.CMD_USER);
                    moreMessage.setMsgId(instructionRecord.getId());
                    moreMessage.setMsgTitle("查岗");
                    moreMessage.setMsgTxt("进行查岗了，请收到消息点击确认，谢谢合作！");
                    redisService.convertAndSend("channel:moreMessage",moreMessage);
                    /*CommonWebSocket webSocket=new CommonWebSocket();
                    log.info("推送用户数：【{}】",unitUserIds.size());
                    JSONObject obj = new JSONObject();
                    obj.put(WebsocketConstant.MSG_CMD, WebsocketConstant.CMD_USER);
                    obj.put(WebsocketConstant.MSG_ID, instructionRecord.getId());
                    obj.put(WebsocketConstant.MSG_TITLE, "查岗");
                    obj.put(WebsocketConstant.MSG_TXT,"进行查岗了，请收到消息点击确认，谢谢合作！" );

                    String[] unitIds=(String[]) (unitUserIds.toArray(new String[ unitUserIds.size()]));
                    String[] userId={"6"};
                    webSocket.sendMoreMessage(userId, obj.toJSONString());*/
                }else{
                    log.info("数据插入失败，不推送消息");
                }
            return CommonResult.success("添加成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 修改指令执行记录信息
     */
    @AutoLog(value = "指令执行记录-修改指令执行记录信息")
    @ApiOperation(value = "修改指令执行记录信息", notes = "修改指令执行记录信息")
    @PostMapping("/update")
//    @RequiresPermissions("firemanger/instructionRecord/update")
    public CommonResult update(@Valid @RequestBody InstructionRecord instructionRecord) {
        try {
            instructionRecord.setUpdateTime(new Date());
            instructionRecord.setIsDetermine(0);
            instructionRecord.setReceiveTime(new Date());
//            instructionRecord.setReceiveUnitId(getEnterpriseId());
            instructionRecord.setUpdateBy(getName());
                instructionRecordService.updateById(instructionRecord);
            return CommonResult.success("修改成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 删除指令执行记录信息
     */
    @AutoLog(value = "指令执行记录-删除指令执行记录信息")
    @ApiOperation(value = "删除指令执行记录信息", notes = "删除指令执行记录信息")
    @ApiImplicitParam(paramType = "query", name = "ids", value = "ID数组", dataType = "String", required = true, allowMultiple = true)
    @PostMapping("/delete")
//    @RequiresPermissions("firemanger/instructionRecord/delete")
    public CommonResult delete(@RequestBody String[]ids) {
        try {
                instructionRecordService.removeByIds(Arrays.asList(ids));
            return CommonResult.success("删除成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }
}
